

package org.binarylook.nio;

import java.nio.channels.SocketChannel;
import java.nio.channels.SelectionKey;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.nio.charset.*;
import java.nio.CharBuffer;

public class Spawn {

    private SelectionKey myKey;
    private SocketChannel myChannel;
    Charset charset         = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder  = charset.newEncoder();
    CharsetDecoder decoder  = charset.newDecoder();

    public Spawn(){

    }
    public Spawn(SelectionKey sc){
        this.myKey = sc;
        this.myChannel = (SocketChannel)this.myKey.channel();
    }
    public void SendMessage(String msg){

          try{
                this.myChannel.write(encoder.encode(CharBuffer.wrap(msg)));
          }
          catch(IOException e){
              e.printStackTrace();
          }
        
    }
    public void ReceiveMessage(){

        try{
            ByteBuffer buf = ByteBuffer.allocate(1024);
            int inputsize = this.myChannel.read(buf);
            if (inputsize != -1) {
                buf.flip();
                String msg = decoder.decode(buf).toString();
                System.out.println("Response is ---" + msg);
                SendMessage(msg);
                buf.clear();
            }
        }
        catch(IOException e){
            try{
                System.out.println("clinet connection has been closed");
                this.myChannel.close();
            }
            catch(IOException e1){
                System.out.println("closing exception happendd.");
            }
            //e.printStackTrace();
        }
        
    }

}
